package com.jb.repair;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.HandlerThread;
import android.util.Log;

import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.dao.Db;
import com.jb.repair.dao.QueryDb;
import com.jb.repair.exception.CrashHandler;
import com.jb.repair.util.TimeUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by YL1988 on 2016/3/2 0002.
 */
public class F1Application extends Application {

    private static HandlerThread handlerThread;
    private static List<Activity> activities;
    private static Context applicationContext;
    private static String userId;
    private static String userName;
    private static SharedPreferences sp;
    private static String power_plant_id;
    private static AlarmManager am = null;

    public static void setUserId(String userid) {
        userId = userid;
    }

    public static String getUserId() {
        return userId;
    }

    public static String getUserName() {
        return userName;
    }

    public static String getPowerPlantId() {
        return Db.getInstance(getAppConext()).getPowerPlantId(userId);
    }

    public static void setUserName(String username) {
        userName = username;
    }

    public static String getDbUpdateDate(String userId) {
        Log.i("---", "userId = " + userId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        String time = sp.getString(userId, null);
        if (time == null) {
            Date date = null;
            time = QueryDb.getInstance(getAppConext()).getResentTaskTime(userId);
            if (time == null) {
                date = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 48);
                time = sdf.format(date);
            } else {
                try {
                    date = sdf.parse(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Long lastTime = date.getTime();
                if (System.currentTimeMillis() - lastTime < 1000 * 60 * 60 * 48) {
                    date = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 48);
                    time = sdf.format(date);
                }
            }
        }
        return time;
    }

    public static void setDBUpdateDate(String userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        Long miles = System.currentTimeMillis();
        Date date = new Date(miles);
        String time = sdf.format(date).substring(0, 19);
        sp.edit().putString(userId, time).commit();
    }

    public static void setLedgerUpdateTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        Long miles = System.currentTimeMillis();
        Date date = new Date(miles);
        String time = sdf.format(date).substring(0, 19);
        sp.edit().putString("ledger", time).commit();
    }

    public static String getLedgerUpdateTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        String time = sp.getString("ledger", TimeUtil.getSystemTime(sdf));
        return time;
    }

    /**
     * 网络连接状态
     */
    private static boolean wifiState;


    /**
     * 判断wifi网络状态
     */
    class WifiConnectChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

                switch (info.getState()) {

                    case DISCONNECTED:
                        wifiState = false;
                        break;
                    case CONNECTING:
                        wifiState = true;
                        break;
                    case DISCONNECTING:
                        wifiState = false;
                        break;
                    case CONNECTED:
                        wifiState = true;
                        break;
                    case SUSPENDED:
                        wifiState = true;
                        break;
                    default:
                        break;
                }
            }
        }
    }


    public static Context getAppConext() {
        return applicationContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sp = getSharedPreferences(Constants.SP_NAME, MODE_PRIVATE);
        AppConfig.BASE_URL = sp.getString(Constants.SERVICE_ADDRESS, "http://zhrx.joinbright.com:8113/relay/");
        applicationContext = getApplicationContext();
        if (getResources().getBoolean(R.bool.debug_mode)) {
            // 异常日志捕获
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }
        activities = new ArrayList<Activity>();
        handlerThread = new HandlerThread("F1ApplicationHandlerThread");
        handlerThread.start();

        // 未收到广播之前 判断wifi是否连接上
        try {
            ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mWifi = null;
            mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo gprs = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mWifi != null && mWifi.isConnected()) {
                wifiState = true;
            }

            if (gprs != null && gprs.isConnected()) {
                wifiState = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 动态注册wifi广播接收器，监听网络变化
        WifiConnectChangedReceiver wifiReceiver = new WifiConnectChangedReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        this.registerReceiver(wifiReceiver, filter);
    }

    public static void addActivity(Activity activity) {
        activities.add(activity);
    }

    public static void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    /**
     * 退出应用程序
     */
    public static void exit() {
        handlerThread.getLooper().quit();
        for (Activity activity : activities) {
            activity.finish();
        }
        System.exit(0);
    }

    public static AlarmManager getAlarmManager(){
        if(am == null){
            am = (AlarmManager)getAppConext().getSystemService(Context.ALARM_SERVICE);
        }
        return am;
    }

    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(Build.VERSION.SDK_INT);
        } catch (NumberFormatException e) {
            Log.e("",e.toString());
        }
        return version;
    }
}
